package com.cn.wanxi.IO;

import com.cn.wanxi.IOModel.CompanyIOModel;
import com.cn.wanxi.IOModel.NavIOModel;
import com.cn.wanxi.model.CompanyModel;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.util.IOUtil;

import java.io.*;
import java.util.Arrays;

public class FileModelIO {
    //存储与读取

    //文件的写入
    public static void writeData(String path,String str) {
        File file = new File(path);
        try {
            file.createNewFile();//无论是否存在该文件都重新创建一个文件
            OutputStream outputStream = new FileOutputStream(file);//打开文件写入流
            // 写入数据与分隔符
            outputStream.write((str.substring(str.indexOf("{")+1,str.lastIndexOf("}")).getBytes()));
            outputStream.flush();//刷新此输出流并强制写出所有缓冲的输出字节。
            outputStream.close();//关闭写入流
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //文件的读取
    public static String readData(String path) {
        File file = new File(path);//找到在该地址文件
        boolean isExist = file.exists();//判断之前该地址文件是否存在
        StringBuilder stringBuilder = new StringBuilder();//初始化一个StringBuilder流
        if (isExist) {//如果存在，则进行读取
            try {
                Reader reader = new FileReader(path);//打开文件读取流
                int a = 0;
                while ((a = reader.read()) != -1) {//将读取出的数据赋值给a，如果读取完毕，则会返回-1
                    stringBuilder.append((char) a);//将读取出的数据添加进StringBuilder中
                }
//                System.out.println("stringBuilder:" + stringBuilder);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();//返回存储在StringBuilder中的数据
    }
    //封装model类
    public static String[] inputData(String result,String spilt) {
        String[] data = result.split(spilt);//将读取的数据以分隔符为界分割成数组
        int length = data.length;
        String[] strs = new String[length];
        for (int i = 0; i < length; i++) {//输出数组数据
            strs[i] = data[i].substring(data[i].indexOf("='")+2,data[i].length()-1);
            System.out.println(i + ":" + strs[i]);
        }
        return strs;
    }

    public static String[] inputDataList(String result,String spilt) {
        String[] data = result.split(spilt);//将读取的数据以分隔符为界分割成数组
        int length = data.length;
        String[] strs = new String[length];
        for (int i = 0; i < length; i++) {//输出数组数据
            strs[i] = data[i].substring(data[i].indexOf("=[")+2,data[i].length()-1);
            System.out.println(i + ":" + strs[i]);
        }
        return strs;
    }
    public static void main(String[] args) {

    }
}
